package com.briup.run.web.listener;

import com.briup.run.bean.AccessRecord;
import com.briup.run.service.AccessRecordService;
import com.briup.run.service.impl.AccessRecordServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: vanse(lc))
 * @Date: 2022/10/11-10-11-10:53
 * @Description：监听服务器启动 准备数据
 * <p>
 * 数据库:
 * 关闭服务器 入库数据
 * 定时器每2小时入库
 * 线程池 newSchduledThreadPool
 * Time
 */
@WebListener
public class AccessRecordListener implements ServletContextListener {
    // 启动服务器 触发
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext application = sce.getServletContext();
        // 查数据库记录 AccessRecord
        AccessRecordService accessRecordService = new AccessRecordServiceImpl();
        // 数据库要存的map ip,count
        Map<String, Long> map = accessRecordService.findAll();
        // 页面显示的map 总人数 总访问量
        Map<String, Long> result = new HashMap<>();
//        map.forEach((k,v) -> System.out.println(k+"="+v));
        application.setAttribute("map", map);
        //页面要显示的
        application.setAttribute("result", result);

        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(() -> {
            addAccessRecord(sce);
            // 入库
        }, 3, 60 * 60 * 2, TimeUnit.SECONDS);

    }

    // 关闭服务器 将map(访问数据库) 入库
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        addAccessRecord(sce);
    }

    private void addAccessRecord(ServletContextEvent sce) {
        AccessRecordService accessRecordService = new AccessRecordServiceImpl();
        ServletContext application = sce.getServletContext();
        Map<String, Long> map = (Map<String, Long>) application.getAttribute("map");
        // 添加数据之前 先清空数据库 防止数据重复
        accessRecordService.truncate();
        // 1.调用入库的方法
        // 循环 单个
        // foreach in id ()
        // 批处理 BATCH 每50条 提交一次
        accessRecordService.add(map);
    }
}
